package ru.compscicenter.uno.model;

import java.io.*;
import java.util.Scanner;

/**
 * Created by IntelliJ IDEA.
 * User: Павел
 * Date: 12.11.11
 * Time: 1:23
 * To change this template use File | Settings | File Templates.
 */
public class RulesFileLoader {
    private final Rules rules;

    public RulesFileLoader(Rules rules) {
        this.rules = rules;
    }

    public void load(String filepath) throws IOException {
        File file = new File(filepath);
        try (Scanner scanner = new Scanner(file)) {
            scanner.useDelimiter(System.getProperty("line.separator"));
            while (scanner.hasNextLine()) {
                String pair = scanner.nextLine();

                if (pair.startsWith("/") || pair.startsWith("#") || pair.startsWith(";") || pair.length() == 0 || pair.indexOf('=') == -1) {
                    continue;
                }

                String param[] = pair.split("[=]");
                Rules.Rule key = null;
                Boolean value = null;

                if (param.length > 0) {
                    try {
                        pair.replaceAll('[' + System.getProperty("line.separator") + ']', "");
                        key = Rules.Rule.valueOf(param[0]);
                    } catch (IllegalArgumentException e) {
                        continue;
                    }
                }

                if (param.length > 1) {
                    try {
                        pair.replaceAll('[' + System.getProperty("line.separator") + ']', "");
                        value = Boolean.parseBoolean(param[1]);
                    } catch (IllegalArgumentException e) {
                        continue;
                    }
                }
                rules.set(key, value);
            }
        } catch (IOException e) {
            throw new IOException("Error while loading rules file: " + e.getMessage(), e);
        }
    }

    public void save(String filepath) throws IOException {
        try (FileWriter outFile = new FileWriter(filepath);
             PrintWriter out = new PrintWriter(outFile)) {

            StringBuilder data = new StringBuilder();
            for (Rules.Rule rule : Rules.Rule.values()) {
                data.append(rule.name() + '=' + rules.isActivated(rule) + System.getProperty("line.separator"));
            }
            out.println(data.toString());
            if (out.checkError()) {
                throw new IOException("Error while writing output file");
            }

        } catch (IOException e) {
            throw new IOException("Error while saving rules file: " + e.getMessage(), e);
        }
    }
}
